package com.hyfd.task;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.hyfd.common.utils.Base64;
import com.hyfd.common.utils.GetUtil;
import com.hyfd.common.utils.MD5;
import com.hyfd.common.utils.ToolDateTime;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.common.utils.YiGuangAES;
import com.hyfd.dao.mp.OrderDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.rabbitMq.RabbitMqProducer;
import com.hyfd.rabbitMq.SerializeUtil;

@Component
public class JingRunYuanFlowTask {

	@Autowired
	ProviderPhysicalChannelDao providerPhysicalChannelDao;//物理通道信息
	@Autowired
	OrderDao orderDao;//订单
	@Autowired
	RabbitMqProducer mqProducer;//消息队列生产者
	private static Logger log = Logger.getLogger(BoLuoMiNewFlowTask.class);
	
//	@Scheduled(fixedDelay = 60000)
	public void queryBoLuoMiNewOrder(){
		Map<String,Object> map = new HashMap<String,Object>();

		int flag = -1;
		try{
			String id = "0000000104";
			Map<String,Object> channel = providerPhysicalChannelDao.selectByPrimaryKey(id);//获取通道的数据
			String defaultParameter = (String) channel.get("default_parameter");//默认参数
			Map<String,String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
			String queryOrderUrl = paramMap.get("queryOrderUrl");
			String account = paramMap.get("account"); // 渠道商编号 
            String key = paramMap.get("key");// 密钥
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("dispatcherProviderId", id);
			param.put("status", "1");
			List<Map<String,Object>> orderList = orderDao.selectByTask(param);
			for(Map<String,Object> order : orderList){
				String orderId = order.get("orderId")+"";
				map.put("orderId", orderId);
				String timeStamp= ToolDateTime.format(new Date(), "yyyyMMddHHmmss");
	            // 平台订单号
	            String curid = account+","+timeStamp;
	            String curids = Base64.encodeBytes(curid.getBytes());
	            //签名串
	            String signature = sign(key, timeStamp, account);
	            queryOrderUrl=queryOrderUrl+orderId+"?nonce="+curids+"&signature="+signature;
	            String result = ToolHttp.get(false, queryOrderUrl);
				if(null!=result&&!"".equals(result)){
					JSONObject jObject = JSONObject.parseObject(result);
	                String orderNo = jObject.getString("orderNo");
	                String status = jObject.getString("status");
	               
//                	map.put("resultCode", status);
                	if("00002".equals(status)){
                		continue;
                	}else if("00000".equals(status)){
                		flag=1;
                		map.put("resultCode", status+":充值成功");
                	}else {
                		flag=0;
                		map.put("resultCode", status+":充值失败");
                	}
				
				map.put("status", flag);
				mqProducer.sendDataToQueue(RabbitMqProducer.Result_QueueKey, SerializeUtil.getStrFromObj(map));
				}
			}
		}catch(Exception e){
			log.error("景润园流量查询Task出错"+e);
		}
	}
	 /**
	    *@param key 接入密钥
	    *@param timestamp 时间戳
	    *@param account客户账户
	    *@return 加密后的签名值
	    */
	    public static String sign (String key, String timestamp, String account) {
	       String[] arr = new String[]{key, timestamp, account };
	       Arrays.sort(arr);
	       StringBuilder content = new StringBuilder();
	       for (int i = 0; i < arr.length; i++) {
	          content.append(arr[i]);
	       }
	       String signature = null;
	       try {
	          MessageDigest md = MessageDigest.getInstance("SHA-1");
	          byte[] digest = md.digest(content.toString().getBytes("utf-8"));
	          signature =toHexString(digest);
	       } catch (NoSuchAlgorithmException e) {
	          e.printStackTrace();
	       } catch (UnsupportedEncodingException e) {
	          e.printStackTrace();
	       }
	       return signature;
	    }

	    public static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	                'a', 'b', 'c', 'd', 'e', 'f'};
	    public static String toHexString(byte[] bytes) {
	       StringBuilder sb = new StringBuilder(bytes.length * 2);
	       for (int i = 0; i < bytes.length; i++) {
	          sb.append(HEX_DIGITS[(bytes[i] & 0xf0) >>> 4]);
	          sb.append(HEX_DIGITS[bytes[i] & 0x0f]);
	       }
	       return sb.toString();
	    }

	    public static void main(String[] args) {
	    	String curids = "account,2016013015555";
	        String curidss = Base64.encodeBytes(curids.getBytes());
			System.out.println("proiductId="+curidss);
			
		}
	
}
